package com.ljq.consumer;

import java.util.Date;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * jms是规范 mq是实现
 * 
 * @author linjq
 *
 */
public class ConsumerImpl implements Consumer {

	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

	ConnectionFactory connectionFactory;
	Connection connection;
	Session session;

	public void init() {
		try {
			// ConnectionFactory ：连接工厂，JMS 用它创建连接
			connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);

			// Session： 一个发送或接收消息的线程
			connection = connectionFactory.createConnection();

			// 启动
			connection.start();

			// 获取操作连接, false手动提交
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

	public void getMessage(String name) {

		try {
			// 获取队列，
			Queue queue = session.createQueue(name);

			MessageConsumer consumer = session.createConsumer(queue);

			while (true) {
				
				//Thread.sleep(1000);

				TextMessage message = (TextMessage) consumer.receive();
				
				//如果不应答收到，队列不会少
				message.acknowledge();

				if (null != message) {
					System.out.println(new Date() + "\tconsumer:我是消费者，我接收的消息内容是：" + message.getText() );
				} else {
					break;
				}

			}

		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
